<?php
	///////////////////////////////////////////////////////////////////////////////////////////////////
	//	MAIN
	//	WRITTEN BY: TRAVIS THORNTON
	//	12-07-2009
	//
	//	What this page does:
	//	1) Adds a row to the pay period table if the user is in a new pay period
	//	2) Shows a server time adjusted javascript clock
	//	3) Shows all events for the day
	//	4) Allows Clocking In, Clocking Out, Going to Lunch, and Back from Lunch events to be processed based on the last event
	//	5) shows login page if not logged in
	//	6) Sets session variables
	//
	// 	Future work:
	//	1) Password encryption. Easy to add, but didn't have enough time to edit this page and all of the other password related pages
	////////////////////////////////////////////////////////////////////////////////////////////////////
	session_start();
	require_once 'php_includes.php';
	require_once 'payperiod_include.php';
	
	
	// This is custom log on script for this page and does not need to be placed in a function or called twice
	if (isset($_SESSION['tmsUserID']) == FALSE)
	{
		//if we are logging in
		if(($_post['userid']))
		{
			sqlConnect();			
			$sql = 'select EmployeePassword, ManagerID from Employee where EmployeeID = \'' . $_post['userid'] . '\''; 
			
			// Perform Query
			$sqlresult = sqlQuery($sql);

			$result = mysql_result($sqlresult, 0, 0);
			$manager = mysql_result($sqlresult, 0, 1);
			
			sqlExit();
			
			//see if the passwords match
			if( $result && $_post['password'] == $result )
			{
				//SET SESSION
				$_SESSION['tmsUserID'] = $_post['userid'];
				$_SESSION['sessionStartTime'] = time();//session timeout variable
				
				//log login
				logDB("LOGIN");
				
				//if it is a manager, set a session variable so it does not need to be looked up to check
				if($_SESSION['tmsUserID'] == $manager)
				{
					$_SESSION['tmsUserType'] = 1;
				}
				else
				{
					$_SESSION['tmsUserType'] = 0;
				}

			}
			//bad password or user
			else
			{
				$_SESSION['errorMessage'] = "Incorrect employee id or password.";
				include "error.php";//include the error
				exit();//exit this code
			}		
		}
		else
		{ 	
			//Not logged on and not logging on. Show login info
			//This will only be called on main.php
			include "login.php";
			exit();
		}
	}
	
	//no message
	$php_message  = "";
	
	//make sure there is a current period row in the db for this user
	checkDBPeriod($_SESSION['tmsUserID']);	
	
	//Get and save the day offset for the db row
	$curr_date = date("Y-m-d");
	$day_offset = 1;
	
	// GET THE DAY OFFSET
	for($n = 0; $n < 14; ++$n)
	{
		$look_date = date("Y-m-d", strtotime($global_current_period_start . " + " . $n . " day"));
		
		//if it matches, save offset +1
		if($look_date == $curr_date)
		{
			$day_offset = $n + 1;
		}
	}
	
	//This handles the events
	if($_post['event'])
	{
		//get the current day events
		sqlConnect();
		$sql = "SELECT Entry" . $day_offset . " FROM PayPeriod WHERE EmployeeID = '" . $_SESSION['tmsUserID'] . "' AND PeriodStart LIKE('" . $global_current_period_start . "')";
		$results = sqlQuery($sql);
		$timestamp = date("Y-m-d H:i");
		
		//event we are adding
		$new_event = $_post['event'] . '@' . $timestamp;
		
		//if it is in the current event string, fail. we do not want 2 logins at the same time
		if(strstr(mysql_result($results, 0, 0), $new_event) == false)
		{
			//clock in event
			if($_post['event'] == "1")
			{	
				$event = 0;
				
				$seperater = "|";
				
				//if first event
				if(trim(mysql_result($results, 0, 0)) == "")
				{		
					$seperater = "";		
				}
	
				$sql = 'UPDATE `' . $dbname . '`.`PayPeriod` SET Entry' . $day_offset . ' = \'' . mysql_result($results, 0, 0) . $seperater . $event . '@' . $timestamp . ':00\' WHERE EmployeeID = \'' . $_SESSION['tmsUserID'] . '\' AND PeriodStart = \'' .  $global_current_period_start . '\'';
				$results = sqlQuery($sql);	
			}
			//clock out
			else if($_post['event'] == "2")
			{	
				$event = 1;

				$sql = 'UPDATE `' . $dbname . '`.`PayPeriod` SET Entry' . $day_offset . ' = \'' . mysql_result($results, 0, 0) . '|' . $event . '@' . $timestamp . ':00\' WHERE EmployeeID = \'' . $_SESSION['tmsUserID'] . '\' AND PeriodStart = \'' .  $global_current_period_start . '\'';
				$results = sqlQuery($sql);	
			}
			//to lunch
			else if($_post['event'] == "3")
			{	
				$event = 2;
				
				$sql = 'UPDATE `' . $dbname . '`.`PayPeriod` SET Entry' . $day_offset . ' = \'' . mysql_result($results, 0, 0) . '|' . $event . '@' . $timestamp . ':00\' WHERE EmployeeID = \'' . $_SESSION['tmsUserID'] . '\' AND PeriodStart = \'' .  $global_current_period_start . '\'';
				$results = sqlQuery($sql);	
			}
			//back from lunch
			else if($_post['event'] == "4")
			{	
				$event = 3;
			
					$sql = 'UPDATE `' . $dbname . '`.`PayPeriod` SET Entry' . $day_offset . ' = \'' . mysql_result($results, 0, 0) . '|' . $event . '@' . $timestamp . ':00\' WHERE EmployeeID = \'' . $_SESSION['tmsUserID'] . '\' AND PeriodStart = \'' .  $global_current_period_start . '\'';
					$results = sqlQuery($sql);	
			}
		}
		else
		{
			//error, 2 events @ same time
			$php_message  = "A similar event with the same timestamp has already been added. Please try again.";
		}
		
		sqlExit();	
	}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <title>Payroll and Timesheet Management Website</title>
    <link rel="stylesheet" type="text/css" href="styles.css"/>
	<script type="text/javascript" src="clock.js"></script>
  </head>
  <body onload="javascript:servertime(<?php $time = date("H") . "," . date("i"). "," . date("s"); echo $time; ?>);">
  
	<?php writeHeader(); ?>
	
	<?php
	//get admin message
	sqlConnect();
	$sql = "SELECT Message FROM Messages WHERE User = 'ADMIN'";
	$results = sqlQuery($sql);
	sqlExit();
		
	//if it is there, display it
	if(mysql_result($results, 0, 0) && trim(mysql_result($results, 0, 0)) != "")
	{
		echo "<div class=\"system_msg_title\">";
		echo "	Admin Message:";
		echo "</div>";
		echo "<div class=\"system_msg\">";
		echo mysql_result($results, 0, 0);
		echo "<br/></div>";
	}

	//get manager message
	sqlConnect();
	
	//get user's manager
	$sql = "SELECT ManagerID FROM Employee WHERE EmployeeID = '" . $_SESSION['tmsUserID'] . "'";
	$mgr_results = sqlQuery($sql);	
		
	//get manager message
	$sql = "SELECT Message FROM Messages WHERE User = '" . mysql_result($mgr_results, 0, 0) . "'";
	$results = sqlQuery($sql);
	sqlExit();
		
	//display it if needed
	if(mysql_result($results, 0, 0) && trim(mysql_result($results, 0, 0)) != "")
	{
		echo "<div class=\"system_msg_title\">";
		echo "	Manager Message:";
		echo "</div>";
		echo "<div class=\"system_msg\">";
		echo mysql_result($results, 0, 0);
		echo "<br/></div>";
	}

	//message if needed
	if($php_message != "")
	{
		echo "<p class=\"php_message\">";
		echo $php_message;
		echo "</p>";
	}
	?>
	<div class="center">
	<!-- Clock div -->
	<div class="clock" id="clock"></div>
	
	<!-- These are the messages for the day clock in until clock out-->
	<p class="message">
	<?php
	//get user's daily messages
	sqlConnect();
	$sql = "SELECT Entry" . $day_offset . " FROM PayPeriod WHERE EmployeeID = '" . $_SESSION['tmsUserID'] . "' AND PeriodStart LIKE('" . $global_current_period_start . "')";
	$results = sqlQuery($sql);
	sqlExit();
	
	//if not empty
	if(trim(mysql_result($results, 0, 0)) != "")
	{
		//turn data into an array
		$data = explode("|", mysql_result($results, 0, 0));
		
		for($i = 0; $i < count($data); ++$i)
		{
			//extract useful info from it
			$info = explode("@", $data[$i]);
			$dateinfo = explode(" ", $info[1]);
			$time = explode(":", $dateinfo[1]);
			
			//if it is a 4, don't display it
			if($info[0] != "4")
			{
				//show event
				switch($info[0])
				{
					case "0":
						echo "Clock in";
					break;
									
					case "1":
						echo "Clock out";
					break;
									
					case "2":
						echo "To lunch";
					break;
									
					case "3":
						echo "Back from lunch";
					break;
					
					default:
						echo"Error";
				}
				
				//format the time to 12hr format
				$period = "AM";
				if($time[0] >= 12)
				{
					$period = "PM";
					if($time[0] > 12)
					{
						$time[0] = $time[0] - 12;
					}
				}
				
				//show time
				echo  " at " . $time[0] . ":" . $time[1] . " " . $period . "<br/>\n";
			}
		}
	}	
	?>
	<br/>
	</p>
	
	<?php
	//Handle the form buttons
	$data = explode("|", mysql_result($results, 0, 0));
		
	//set last event flag to logout (clock in only avail)
	$last_event = 1;

	//find the final event in the entry data
	if(trim(mysql_result($results, 0, 0)) != "")
	{
		for($i = 0; $i < count($data); ++$i)
		{
			$info = explode("@", $data[$i]);
			if($info[0] != "4") { $last_event = $info[0];}//don't worry about 4
		}
	}
		
	//based on the last event, determine what the user can do
	switch($last_event)
	{
		case 0://last was clock in or back from lunch
		case 3:
			echo "	<form action=\"main.php\" method=\"post\">\n";
			echo "	<div class=\"actions\">\n";
			echo "	<p>\n";
			echo "	<input type=\"hidden\" name=\"event\" value=\"3\" />\n";
			echo "	<input type=\"submit\" value=\"To Lunch\" class=\"button\"/>\n";
			echo "	</p>\n";
			echo "	</div>\n";
			echo "	</form>\n";		
			echo "	<form action=\"main.php\" method=\"post\">\n";
			echo "	<div class=\"actions\">\n";
			echo "	<p>\n";
			echo "	<input type=\"hidden\" name=\"event\" value=\"2\" />\n";
			echo "	<input type=\"submit\" value=\"Clock Out\" class=\"button\"/>\n";
			echo "	</p>\n";
			echo "	</div>\n";
			echo "	</form>\n";
		break;
		case 1://last was clock out
			echo "	<form action=\"main.php\" method=\"post\">\n";
			echo "	<div class=\"actions\">\n";
			echo "	<p>\n";
			echo "	<input type=\"hidden\" name=\"event\" value=\"1\" />\n";
			echo "	<input type=\"submit\" value=\"Clock In\" class=\"button\"/>\n";
			echo "	</p>\n";
			echo "	</div>\n";
			echo "	</form>\n";
		break;
		case 2://last was to lunch
			echo "	<form action=\"main.php\" method=\"post\">\n";
			echo "	<div class=\"actions\">\n";
			echo "	<p>\n";
			echo "	<input type=\"hidden\" name=\"event\" value=\"4\" />\n";
			echo "	<input type=\"submit\" value=\"Back From Lunch\" class=\"button\"/>\n";
			echo "	</p>\n";
			echo "	</div>\n";
			echo "	</form>\n";
		break;
	}
	?>
	</div>
  </body>
</html>